package com.example.ajshu.common.utils;

import java.security.MessageDigest;

/**
 * Created by shu.aojun@qq.com on 2016/11/9-23:31
 * Copyright 2016 ao jun shu
 */
public class MD5EncryptUtils {
    private final static char hexDigits[] = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public final static String MD5(String s) {
        try {
            if (s != null && !"".equals(s.trim())) {
                byte[] strTemp = s.getBytes("utf-8");
                MessageDigest mdTemp = MessageDigest.getInstance("MD5");
                mdTemp.update(strTemp);
                byte[] md = mdTemp.digest();
                return hexStr(md);
            } else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String hexStr(byte[] md) {
        int j = md.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = md[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }
}
